#!/bin/bash
if [ -z "$PROJECT_BASE" ]; then
   echo "You have to define PROJECT_BASE variable"
   exit 1
fi
. $PROJECT_BASE/src/test/resources/testEnv.sh

function run(){
    local fileTest=`find . -name "test*".sh|grep -v "testEnv.sh"`
    local failedTest=""
    local current_dir=$PWD
    local totalTests=0
    local totalErrorTests=0

    for i in $fileTest; do
        cd $current_dir
        echo ========== Run test $i ===============
        cd `dirname $i`
        SHCOV "./`basename $i`" >$current_dir/.testResult
        local error=`cat $current_dir/.testResult|tail -1|grep "FAILED"|cut -d'=' -f2|cut -d')' -f1`
        local nTests=`cat $current_dir/.testResult|tail -4|grep "tests."|grep "Ran"|cut -d' ' -f2`
        if [ -z "$nTests" ]; then
            nTests=`cat $current_dir/.testResult|tail -4|grep "test."|grep "Ran"|cut -d' ' -f2`
        fi
        totalTests=$(($totalTests+$nTests));
        if [ "$error" != "" ]; then
            cat $current_dir/.testResult
            totalErrorTests=$(($totalErrorTests+$error));
            failedTest="\n ${failedTest} $i Total Test:${nTests} Ok: $(($nTests-$error)) Failed: ${error}"
        else
            echo "OK"
        fi
        rm $current_dir/.testResult
    done;
    
    cd $current_dir
    SHLCOV
    
    if [ "${#failedTest}" != "0" ]; then
        echo =========================================
        echo Failed tests:
        echo -e $failedTest
    fi
    echo ==============================================
    echo "Summarize($totalTests Tests):"
    echo "  PASS Tests: $(($totalTests-$totalErrorTests))"
    local result=$(($totalErrorTests * 100))
    result=`echo $result/$totalTests|bc -l`
    echo "  FAIL Tests: $totalErrorTests (${result}%)"
    echo ==============================================
    return $totalErrorTests
}

if [  "$#" == "1"  -a  "$1" == "--with-coverage" ] ; then
    COVERAGE="true"
    #workaround. It's necessary to calculate coverage in scripts
    run $*
fi
run $*
